library sp_util;

import 'dart:async';
import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:synchronized/synchronized.dart';

/**
 * @author: slc
 * 基于SharedPreferences缓存工具类
 */
class SpCacheUtil {
  static SpCacheUtil? _singleton;
  static SharedPreferencesWithCache? _prefs;
  static Lock _lock = Lock();

  static Future<SpCacheUtil?> getInstance() async {
    if (_singleton == null) {
      await _lock.synchronized(() async {
        if (_singleton == null) {
          // keep local instance till it is fully initialized.
          // 保持本地实例直到完全初始化。
          var singleton = SpCacheUtil._();
          await singleton._init();
          _singleton = singleton;
        }
      });
    }
    return _singleton;
  }

  SpCacheUtil._();

  Future _init() async {
    _prefs = await SharedPreferencesWithCache.create(cacheOptions: SharedPreferencesWithCacheOptions());
  }

  static Future<void>? reload() {
    return _prefs?.reloadCache();
  }

  static bool isInitialized() {
    return _prefs != null;
  }

  static SharedPreferencesWithCache? getSp() {
    return _prefs;
  }
}
